<?php

namespace App\Http\Controllers\Home;

use App\Models\Bankcard;
use App\Models\Image;
use App\Models\JifenProduct;
use App\Models\ProdCategory;
use App\Models\Product;
use App\Models\Search;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * @group 前台接口文档
 * @title 首页模块接口
 * @author chenke
 * @description 酒庄前台首页板块接口
 * @header name:Lang type:string require:1 desc:语言类型(en或zn)
 *  */
class Index extends Base
{
    /**
     * @title 轮播图列表
     * @description 前台轮播图
     * @url /api/index/carousel
     * @method GET
     * @module 轮播图板块
     * @author chenke
     * @param name:type type:int require:1 default:3 other: desc:轮播类型(3首页轮播,5餐桌预定轮播)
     * @return code:错误码
     * @return message:错误提示
     * @return data:图片信息@
     * @data id:图片ID title:图片英文名 title_zn:图片中文名 src:图片地址 type:图片类型(同参数) rid:图片关联ID created_at:图片添加时间
     */
    public function carouselList(Request $request){
        try {
            $lang = $request->header('Lang')?$request->header('Lang'):'zn';
            $type = $request->get('type');
            if(!in_array($type,[3,5])){
                return response()->json([
                    'code'=>1,
                    'message'=>$this->lang['IN'][$lang]
                ]);
            }
            $where = [
                ['type','=',$type]
            ];
            $result = (new Image())->where($where)->get();
            return response()->json([
                'code'=>0,
                'data'=>$result->toArray()
            ]);
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$lang]
            ]);
        }
    }

    /**
     * @title 获取平台付款银行卡列表
     * @description  平台付款银行卡列表
     * @url /api/index/cards
     * @method GET
     * @module 平台银行卡板块
     * @author chenke
     * @return code:错误码
     * @return message:错误提示
     * @return data:图片信息@
     * @data id:银行卡ID cardowner:卡主姓名 bankname:归属银行名称 bankcard:银行卡号
     */
    public function bankCardList(Request $request){
        try {
            $lang = $request->header('Lang')?$request->header('Lang'):'zn';
            $result = (new Bankcard())->where('uid',0)->get();
            return response()->json([
                'code'=>0,
                'data'=>$result->toArray()
            ]);
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$lang]
            ]);
        }
    }

    /**
     * @title 商品分页列表
     * @description 商品分页列表
     * @url /api/index/products
     * @method GET
     * @module 商品板块
     * @author chenke
     * @param name:limit type:int require:1 default:1 other: desc:每页数据条数
     * @param name:page type:int require:1 default:1 other: desc:当前页数
     * @param name:searchcontent type:string require:0 default: other: desc:输入框搜索内容(商品英文名或中文名)
     * @param name:order type:json require:0 default:销量倒序 other: desc:排序(如{rprice:'asc',salenum:'desc'}代表价格顺序，销量倒序)
     * @param name:searchtype type:string require:0 default: other: desc:搜索类型(类型ID，多个类型用半圆角逗号隔开.如:1,2,3)
     * @return code:错误码
     * @return message:错误提示
     * @return data:商品信息@
     * @data id:商品ID cids:商品分类ID,多个以半圆角逗号隔开 proname:商品英文名 proname_zn:中文名 image:商品主图 mprice:商品价格 rprice:活动价格 salenum:商品销量 content:商品详情
     */
    public function prodlList(Request $request){
        $lang = $request->header('Lang')?$request->header('Lang'):'zn';
        $token = $request->header('Token')?$request->header('Token'):'';
        try {
            $data = $request->all();
            $limit = $data['limit'];
            $page = $data['page'];
            $searchCont = (isset($data['searchcontent']) && $data['searchcontent'])?$data['searchcontent']:'';
            $order = (isset($data['order']) && $data['order'])?$data['order']:json_encode(['salenum'=>'desc']);
            $searchtype = (isset($data['searchtype']) && $data['searchtype'])?$data['searchtype']:'';
            $where = [
                ['deleted_at','=',null]
            ];
            $model = new Product();
            $model = $model->where($where);
            $user = "";
            if($searchCont){
                $model = $model->where(function($query)use($searchCont){
                    $query->where('proname','like','%'.$searchCont.'%')->orWhere('proname_zn','like','%'.$searchCont.'%');
                });
                if($token){
                    $user = (new User())->where('token',$token)->first();
                    if(!$user){
                        return response()->json([
                            'code'=>50002,
                            'message'=>$this->lang['LOGIN_EXPIRE'][$lang]
                        ]);
                    }
                    $smodel = new Search();
                    $search = $smodel->where([
                        ['content','=',$searchCont],['uid','=',$user->id]
                    ])->first();
                    if(!$search){
                        DB::table('searches')->insertGetId(['content'=>$searchCont,'uid'=>$user->id,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')]);
                    }else{
                        $search->times += 1 ;
                        $search->save();
                    }
                }else{
                    DB::table('searches')->insertGetId(['content'=>$searchCont,'uid'=>0,'created_at'=>date('Y-m-d H:i:s')]);
                }
            }else{
                if($token){
                    $user = (new User())->where('token',$token)->first();
                }
            }
            if($searchtype){
                $types = explode(',',$searchtype);
                foreach ($types as $t){
                    $model = $model->whereRaw('FIND_IN_SET(?,cids)', [$t]);
                }
            }
            $order = json_decode($order,true);
            foreach ($order as $key=>$v){
                $model = $model->orderBy($key,$v);
            }
            $result = (new Product())->getList($model,$page,$limit,$user,$lang);
            return response()->json($result);
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$lang]
            ]);
        }
    }

    /**
     * @title 积分商品分页列表
     * @description 积分商品分页列表
     * @url /api/index/jfenprods
     * @method GET
     * @module 积分商品板块
     * @author chenke
     * @param name:limit type:int require:1 default:1 other: desc:每页数据条数
     * @param name:page type:int require:1 default:1 other: desc:当前页数
     * @return code:错误码
     * @return message:错误提示
     * @return data:商品信息@
     * @data id:商品ID proname:商品英文名 proname_zn:中文名 image:商品主图 price:商品价格 coin:兑换所需积分 salenum:商品销量 content:商品详情
     */
    public function jifenProdList(Request $request){
        $lang = $request->header('Lang')?$request->header('Lang'):'zn';
        try {
            $data = $request->all();
            $limit = $data['limit'];
            $page = $data['page'];
            $where = [
                ['deleted_at','=',null]
            ];
            $model = new JifenProduct();
            $model = $model->where($where);
            $offset = ($page-1) * $limit;
            $total =  $model->count();  //获取模型总数据条数
            $result = $model->offset($offset)->limit($limit)->get()->toArray();
            $data = array(
                'total'=>$total,
                'list'=>$result
            );
            return response()->json([
                'code'=>0,
                'data'=>$data
            ]);
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$lang]
            ]);
        }
    }

    /**
     * @title 获取商品详情
     * @description 获取商品详情
     * @url /api/index/proddetail
     * @method GET
     * @module 商品板块
     * @author chenke
     * @param name:id type:string require:1 default: other: desc:商品ID
     * @return code:错误码
     * @return message:错误提示
     * @return data:商品信息@
     * @data id:商品ID cids:商品分类ID,多个以半圆角逗号隔开 catenames:商品所有分类名称 proname:商品英文名 proname_zn:中文名 image:商品主图 mprice:商品价格 rprice:活动价格 salenum:商品销量 content:商品详情
     */
    public function productDetail(Request $request){
        $lang = $request->header('Lang')?$request->header('Lang'):'zn';
        $token = $request->header('Token')?$request->header('Token'):'';
        try {
            $id = $request->get('id');
            $result = Product::find($id);
            if($result){
                $cids =  explode(',',$result->cids);
                $name = $lang=='zn'?'catename_zn':'catename';
                $cates = (new ProdCategory())->whereIn('id',$cids)->pluck($name)->toArray();
                $catenames = implode(',',$cates);
                $imgs = (new Image())->where([
                    ['type','=',1],['rid','=',$id]
                ])->pluck('src')->toArray();
                $return = $result->toArray();
                $discount = 100;
                if($token){
                    $user = (new User())->where('token',$token)->first();
                    if(!$user){
                        return response()->json([
                            'code'=>50002,
                            'message'=>$this->lang['LOGIN_EXPIRE'][$lang]
                        ]);
                    }
                    $discounts = (new \App\Models\Base())->getProdDiscount($user,$id);
                    $discount = $discounts['discount'];
                }
                $return['rprice'] = $return['rprice'] * $discount / 100 ;
                $return['catenames'] = $catenames;
                $return['imgs'] = $imgs;
                return response()->json([
                    'code'=>0,
                    'data'=>$return
                ]);
            }else{
                return response()->json([
                    'code'=>1,
                    'message'=>$this->lang['GET_FAIL'][$lang]
                ]);
            }
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$lang]
            ]);
        }
    }

    /**
     * @title 获取积分商品详情
     * @description 获取积分商品详情
     * @url /api/index/jfproddetail
     * @method GET
     * @module 积分商品板块
     * @author chenke
     * @param name:id type:string require:1 default: other: desc:商品ID
     * @return code:错误码
     * @return message:错误提示
     * @return data:商品信息@
     * @data id:商品ID proname:商品英文名 proname_zn:中文名 image:商品主图 mprice:商品价格 rprice:活动价格 salenum:商品销量 content:商品详情
     */
    public function jifenProdDetail(Request $request){
        $lang = $request->header('Lang')?$request->header('Lang'):'zn';
        try {
            $id = $request->get('id');
            $result = JifenProduct::find($id);
            if($result){
                $imgs = (new Image())->where([
                    ['type','=',2],['rid','=',$id]
                ])->pluck('src')->toArray();
                $return = $result->toArray();
                $return['imgs'] = $imgs;
                return response()->json([
                    'code'=>0,
                    'data'=>$return
                ]);
            }else{
                return response()->json([
                    'code'=>1,
                    'message'=>$this->lang['GET_FAIL'][$lang]
                ]);
            }
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$lang]
            ]);
        }
    }

    /**
     * @title 获取商品分类
     * @description 获取所有的商品分类或单个分类信息
     * @url /api/index/cates
     * @method GET
     * @module 商品板块
     * @author chenke
     * @param name:id type:string require:0 default: other: desc:分类ID
     * @return code:错误码
     * @return message:错误提示
     * @return data:分类信息@
     * @data id:分类ID catename:分类英文名 catename_zn:分类中文名 created_at:创建时间
     */
    public function categories(Request $request){
        $lang = $request->header('Lang')?$request->header('Lang'):'zn';
        try {
            $data = $request->all();
            $id = (isset($data['id']) && $data['id'])?$data['id']:'';
            $where = [];
            if($id){
                $where[] = ['id','=',$id];
            }
            $result = (new ProdCategory())->where($where)->get();
            if($result){
                $return = $result->toArray();
                if($id){
                    $return = $return[0];
                }
                return response()->json([
                    'code'=>0,
                    'data'=>$return
                ]);
            }else{
                return response()->json([
                    'code'=>1,
                    'message'=>$this->lang['GET_FAIL'][$lang]
                ]);
            }
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$lang]
            ]);
        }
    }

    /**
     * @title 获取商品搜索记录
     * @description 获取用户商品搜索记录或所有热门搜索
     * @url /api/index/searches
     * @method GET
     * @module 商品板块
     * @author chenke
     * @param name:uid type:string require:0 default: other: desc:用户ID
     * @return code:错误码
     * @return message:错误提示
     * @return data:商品信息@
     * @data userdata:用户数据@ hotsdata:热门搜索@
     * @userdata id:搜索ID uid:用户ID content:搜索内容 times:搜索次数 created_at:创建时间
     * @hotsdata id:搜索ID uid:用户ID content:搜索内容 times:搜索次数 created_at:创建时间
     */
    public function searchHistory(Request $request){
        $lang = $request->header('Lang')?$request->header('Lang'):'zn';
        try {
            $data = $request->all();
            $uid = (isset($data['uid']) && $data['uid'])?$data['uid']:0;
            $where = [];
            $model = new Search();
            if($uid){
                $where[] = ['uid','=',$uid];
                $model = $model->where($where);
                $userResult = $model->selectRaw('sum(times) as sumtime,content')->offset(0)->limit(10)->groupBy('content')->orderBy('sumtime','desc')->get()->toArray();
            }else{
                $userResult=[];
            }
            $result = $model->selectRaw('sum(times) as sumtime,content')->offset(0)->limit(10)->groupBy('content')->orderBy('sumtime','desc')->get();
            if($result){
                $return = $result->toArray();
                return response()->json([
                    'code'=>0,
                    'data'=>[
                        'userdata'=>$userResult,
                        'hotsdata'=>$return
                    ]
                ]);
            }else{
                return response()->json([
                    'code'=>1,
                    'message'=>$this->lang['GET_FAIL'][$lang]
                ]);
            }
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$lang]
            ]);
        }
    }

    /**
     * @title 根据分类获取商品
     * @description 根据分类获取商品
     * @url /api/index/cateprods
     * @method GET
     * @module 商品板块
     * @author chenke
     * @param name:cids type:string require:0 default: other: desc:分类id(多个用半圆角逗号隔开)
     * @return code:错误码
     * @return message:错误提示
     * @return data:商品信息@
     * @data userdata:用户数据@ hotsdata:热门搜索@
     * @userdata id:搜索ID uid:用户ID content:搜索内容 times:搜索次数 created_at:创建时间
     * @hotsdata id:搜索ID uid:用户ID content:搜索内容 times:搜索次数 created_at:创建时间
     */
    public function getCateProducts(Request $request){
        $lang = $request->header('Lang')?$request->header('Lang'):'zn';
        try {
            $data = $request->all();
            $cids =explode(',',$data['cids']);
            $prods = [];
            foreach ($cids as $cid){
                $prods[] = (new Product())->where('deleted_at',null)->whereRaw('FIND_IN_SET(?,cids)', [$cid])->get()->toArray();
            }
            return response()->json([
                'code'=>0,
                'data'=>$prods
            ]);
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$lang]
            ]);
        }
    }

}
